<script lang="ts" setup>
import type {
  GridInstance as VxeGridInstance,
  VxeGridListeners,
  VxeGridProps,
} from '#/adapter/vxe-table';

import { computed, onMounted, ref } from 'vue';

import { Button, Form, Input, message, Modal, Select } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { SoftwareApi } from '#/api/core/Software';

// 表格引用
const gridRef = ref<VxeGridInstance>();

// 存储表格数据
const tableData = ref<SoftwareApi.DeviceInfo[]>([]);

// 存储设备类型数据
const deviceTypes = ref<SoftwareApi.DeviceTypeInfo[]>([]);

// 添加更新表单的数据结构
const updateForm = ref<Partial<SoftwareApi.UpdateDeviceParams>>({
  app_version: '',
  app_download_url: '',
});

// 添加控制弹窗显示的变量
const updateModalVisible = ref(false);
const currentDeviceId = ref<number>();

// 添加加载状态
const confirmLoading = ref(false);

// 表格配置
const gridOptions = computed<VxeGridProps<SoftwareApi.DeviceInfo>>(() => ({
  columns: [
    { field: 'app_type', title: '软件类型', width: 100 },
    { field: 'app_name', title: '软件名称', width: 200 },
    { field: 'app_version', title: '软件版本', width: 100 },
    {
      field: 'app_download_url',
      title: '软件下载地址',
      slots: {
        default: 'downloadUrl',
      },
    },
    {
      title: '操作',
      width: 120,
      slots: {
        default: 'operation',
      },
    },
  ],
  data: tableData.value,
  sortConfig: {
    multiple: true,
  },
  showOverflow: true,
  showFooter: false,
  pagerConfig: false,
}));

const gridEvents: VxeGridListeners<SoftwareApi.DeviceInfo> = {};

const [Grid, gridApi] = useVbenVxeGrid({
  gridEvents,
  gridOptions: gridOptions.value,
});

// 搜索表单数据
const searchForm = ref({
  app_type: 0,
});

// 加载设备类型数据
async function loadDeviceTypes() {
  try {
    const data = await SoftwareApi.getDevicesTypeList();
    // console.log(data,"data")
    deviceTypes.value = [{ app_type: 0, app_name: '全部' }, ...data];
  } catch {
    message.error('获取设备类型列表失败');
  }
}

// 加载表数据
async function loadData() {
  try {
    gridApi.setLoading(true);
    const data = await SoftwareApi.getDevicesList({
      app_type: searchForm.value.app_type,
    });

    tableData.value = data;
    gridApi.setGridOptions({
      data: tableData.value,
    });
  } catch {
    message.error('获取设备列表失败');
    tableData.value = [];
  } finally {
    gridApi.setLoading(false);
  }
}

// 搜索方法
function handleSearch() {
  loadData();
}

// 修改复制功能函数
const handleCopyUrl = async (url: string) => {
  try {
    // 首选方案：使用 Clipboard API
    if (navigator.clipboard && window.isSecureContext) {
      await navigator.clipboard.writeText(url);
      message.success('复制成功');
      return;
    }

    // 后备方案：使用 execCommand
    const textarea = document.createElement('textarea');
    textarea.value = url;
    textarea.style.position = 'fixed';
    textarea.style.left = '-9999px';
    textarea.style.top = '0';
    document.body.append(textarea);
    textarea.focus();
    textarea.select();

    const successful = document.execCommand('copy');
    textarea.remove();

    if (successful) {
      message.success('复制成功');
    } else {
      throw new Error('复制失败');
    }
  } catch {
    message.error('复制失败');
    // console.error('复制出错:', err);
  }
};

// 修改打开弹窗的方法
const handleUpdate = (row: SoftwareApi.DeviceInfo) => {
  // console.log('完整的行数据:', row);

  currentDeviceId.value = row.app_type; // 使用 app_type 作为 id
  updateForm.value = {
    app_version: row.app_version || '',
    app_download_url: row.app_download_url || '',
  };

  // console.log('更新表单数据:', {
  //   id: currentDeviceId.value,
  //   form: updateForm.value
  // });

  updateModalVisible.value = true;
};

// 修改提交更新的方法
const handleUpdateSubmit = async () => {
  // console.log('提交时的数据:', {
  //   id: currentDeviceId.value,
  //   form: updateForm.value
  // });

  if (!currentDeviceId.value) {
    message.error('数据异常，请重试');
    return;
  }

  // 验证表单数据
  if (!updateForm.value.app_version?.trim()) {
    message.error('请输入软件版本');
    return;
  }
  if (!updateForm.value.app_download_url?.trim()) {
    message.error('请输入下载地址');
    return;
  }

  try {
    confirmLoading.value = true;
    await SoftwareApi.updateDeviceSetting({
      id: currentDeviceId.value,
      ...(updateForm.value as SoftwareApi.UpdateDeviceParams),
    });
    message.success('更新成功');
    updateModalVisible.value = false;
    loadData(); // 重新加载数据
  } catch {
    message.error('更新失败');
  } finally {
    confirmLoading.value = false;
  }
};

onMounted(() => {
  loadDeviceTypes();
  loadData();
});
</script>

<template>
  <div class="p-4">
    <!-- 搜索表单 -->
    <Form class="mb-4" layout="inline">
      <Form.Item label="设备类型">
        <Select
          v-model:value="searchForm.app_type"
          style="width: 200px"
          @change="handleSearch"
        >
          <Select.Option
            v-for="type in deviceTypes"
            :key="type.app_type"
            :value="type.app_type"
          >
            {{ type.app_name }}
          </Select.Option>
        </Select>
      </Form.Item>
    </Form>

    <div class="vp-raw w-full">
      <Grid ref="gridRef">
        <template #downloadUrl="{ row }">
          <span
            class="cursor-pointer text-blue-500 hover:text-blue-700"
            @click="handleCopyUrl(row.app_download_url)"
          >
            {{ row.app_download_url }}
          </span>
        </template>

        <template #operation="{ row }">
          <Button size="small" type="primary" @click="handleUpdate(row)">
            更新软件
          </Button>
        </template>
      </Grid>
    </div>

    <!-- 添加更新软件的弹窗 -->
    <Modal
      v-model:visible="updateModalVisible"
      :confirm-loading="confirmLoading"
      :keyboard="false"
      :mask-closable="false"
      title="更新软件"
      @ok="handleUpdateSubmit"
    >
      <Form layout="vertical">
        <Form.Item label="软件版本" required>
          <Input
            v-model:value="updateForm.app_version"
            placeholder="请输入软件版本"
          />
        </Form.Item>
        <Form.Item label="下载地址" required>
          <Input
            v-model:value="updateForm.app_download_url"
            placeholder="请输入下载地址"
          />
        </Form.Item>
      </Form>
      <template #footer>
        <Button @click="() => (updateModalVisible = false)">取消</Button>
        <Button
          :loading="confirmLoading"
          type="primary"
          @click="handleUpdateSubmit"
        >
          确定
        </Button>
      </template>
    </Modal>
  </div>
</template>
